package com.marvelution.samples.springmetadataattributes.interceptors;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.marvelution.samples.springmetadataattributes.attributes.SampleAttribute;
import com.marvelution.samples.springmetadataattributes.attributes.SampleAttributeSource;

/**
 * @author mark.rekveld
 * 
 */
public class SampleAttributeInterceptor implements MethodInterceptor {

	/**
	 * Apache Commons Logger
	 */
	private static final Log LOG = LogFactory
			.getLog(SampleAttributeInterceptor.class);

	/**
	 * The SampleAttributeSource object to get the SampleAttribute meta data of
	 * a method invocation
	 */
	private SampleAttributeSource sampleAttributeSource;

	/**
     */
	public SampleAttributeInterceptor() {
	}

	/**
	 * {@inheritDoc}
	 */
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object result = null;
		LOG.info("SampleAttributeInterceptor - INVOKE: "
				+ invocation.getMethod());
		SampleAttribute sampleAttribute = this
				.identifySampleAttribute(invocation);
		if (sampleAttribute != null) {
			LOG.info("Sample Attribute Found: " + sampleAttribute.getValue());
			LOG.info("Here we can do something with the SampleAttribute");
			result = invocation.proceed();
		} else {
			LOG.info("No Sample Attribute Found");
			result = invocation.proceed();
		}
		return result;
	}

	/**
	 * Method to find the SampleAttribute for the method invocation
	 * 
	 * @param invocation
	 *            the {@link MethodInvocation} to identify the SampleAttribute
	 *            for
	 * @return SampleAttribute the {@link SampleAttribute} if a
	 *         {@link SampleAttribute} is found for the invocation,
	 *         <code>null</code> otherwise
	 */
	private SampleAttribute identifySampleAttribute(MethodInvocation invocation) {
		Class targetClass = null;
		if (invocation.getThis() != null) {
			targetClass = invocation.getThis().getClass();
		}
		return this.getSampleAttributeSource().getSampleAttribute(
				invocation.getMethod(), targetClass);
	}

	/**
	 * Getter for {@link #sampleAttributeSource}
	 * 
	 * @return SampleAttributeSource
	 */
	public SampleAttributeSource getSampleAttributeSource() {
		return sampleAttributeSource;
	}

	/**
	 * Setter for {@link #sampleAttributeSource}
	 * 
	 * @param SampleAttributeSource
	 */
	public void setSampleAttributeSource(
			SampleAttributeSource sampleAttributeSource) {
		this.sampleAttributeSource = sampleAttributeSource;
	}

}
